import React, { useState } from 'react';
import { Modal, Input, Upload, Button, message, Tabs, Space } from 'antd';
import { UploadOutlined, LinkOutlined } from '@ant-design/icons';
import type { UploadFile, UploadProps } from 'antd';

interface ImageUploadModalProps {
  visible: boolean;
  onCancel: () => void;
  onConfirm: (imageUrl: string) => void;
}

const ImageUploadModal: React.FC<ImageUploadModalProps> = ({
  visible,
  onCancel,
  onConfirm
}) => {
  const [activeTab, setActiveTab] = useState('url');
  const [imageUrl, setImageUrl] = useState('');
  const [uploading, setUploading] = useState(false);
  const [fileList, setFileList] = useState<UploadFile[]>([]);

  const handleUrlConfirm = () => {
    if (!imageUrl.trim()) {
      message.error('请输入图片URL');
      return;
    }
    
    // 简单的URL格式验证
    const urlPattern = /^(https?:\/\/)([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$/;
    if (!urlPattern.test(imageUrl)) {
      message.error('请输入有效的图片URL');
      return;
    }
    
    onConfirm(imageUrl);
    handleClose();
  };

  const handleClose = () => {
    setImageUrl('');
    setFileList([]);
    setActiveTab('url');
    onCancel();
  };

  const uploadProps: UploadProps = {
    name: 'file',
    action: 'http://1.95.134.113:8080/upload',
    headers: {
      'token': 'eyJhbGciOiJIUzI1NiJ9.eyJuYW1lIjoi5bCP6bif5ri45pif6YeOIiwiaWQiOjIsInVzZXJuYW1lIjoiYWRtaW4iLCJleHAiOjE3NTQwMjE5OTR9.seEd8FLNSB0jgT0GOA3mt90uaLsWoXeF9eb38qDIj_w'
    },
    fileList,
    beforeUpload: (file) => {
      const isImage = file.type?.startsWith('image/');
      if (!isImage) {
        message.error('只能上传图片文件!');
        return false;
      }
      const isLt5M = file.size / 1024 / 1024 < 5;
      if (!isLt5M) {
        message.error('图片大小不能超过5MB!');
        return false;
      }
      return true;
    },
    onChange: (info) => {
      setFileList(info.fileList);
      
      if (info.file.status === 'uploading') {
        setUploading(true);
      }
      
      if (info.file.status === 'done') {
        setUploading(false);
        const response = info.file.response;
        
        if (response && response.code === 1 && response.data) {
          const uploadedUrl = response.data.url || response.data;
          message.success('图片上传成功!');
          onConfirm(uploadedUrl);
          handleClose();
        } else {
          message.error('上传失败，请重试');
        }
      }
      
      if (info.file.status === 'error') {
        setUploading(false);
        message.error('上传失败，请重试');
      }
    },
    maxCount: 1,
    accept: 'image/*'
  };

  const tabItems = [
    {
      key: 'url',
      label: (
        <span>
          <LinkOutlined />
          URL链接
        </span>
      ),
      children: (
        <div style={{ padding: '16px 0' }}>
          <Input
            placeholder="请输入图片URL地址"
            value={imageUrl}
            onChange={(e) => setImageUrl(e.target.value)}
            onPressEnter={handleUrlConfirm}
            style={{ marginBottom: 16 }}
          />
          <div style={{ textAlign: 'right' }}>
            <Space>
              <Button onClick={handleClose}>取消</Button>
              <Button type="primary" onClick={handleUrlConfirm}>
                确定
              </Button>
            </Space>
          </div>
        </div>
      )
    },
    {
      key: 'upload',
      label: (
        <span>
          <UploadOutlined />
          上传图片
        </span>
      ),
      children: (
        <div style={{ padding: '16px 0', textAlign: 'center' }}>
          <Upload.Dragger {...uploadProps} style={{ marginBottom: 16 }}>
            <p className="ant-upload-drag-icon">
              <UploadOutlined style={{ fontSize: 48, color: '#1890ff' }} />
            </p>
            <p className="ant-upload-text">点击或拖拽文件到此区域上传</p>
            <p className="ant-upload-hint">
              支持单个文件上传，仅支持图片格式，文件大小不超过5MB
            </p>
          </Upload.Dragger>
          <div style={{ textAlign: 'right' }}>
            <Button onClick={handleClose} disabled={uploading}>
              取消
            </Button>
          </div>
        </div>
      )
    }
  ];

  return (
    <Modal
      title="插入图片"
      open={visible}
      onCancel={handleClose}
      footer={null}
      width={500}
      destroyOnClose
    >
      <Tabs
        activeKey={activeTab}
        onChange={setActiveTab}
        items={tabItems}
      />
    </Modal>
  );
};

export default ImageUploadModal;